﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// IP 地址过滤器
    /// </summary>
    public class IPAddressFilterAttribute : ActionFilterAttribute
    {
        private readonly string _sectionName;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sectionName">配置项名称</param>
        public IPAddressFilterAttribute(string sectionName)
        {
            _sectionName = sectionName;
        }

        /// <summary>
        /// 异步IP地址授权方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
            var valid = context.HttpContext.Connection.RemoteIpAddress.ValidateSafeList(config.GetSafeList(_sectionName));
            if (!valid)
            {
                context.Result = new StatusCodeResult(403);
                return;
            }
            base.OnActionExecuting(context);
        }
    }
}
